{% extends 'base/userinfo.html' %}


{% block head %}
<meta charset="utf-8">
<title>环境配置 管理界面</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/asset/layui/css/layui.css" media="all">
<link rel="stylesheet" href="/asset/css/global.css" media="all">
<script src="/asset/js/js-yaml.min.js"></script>
<script src="/asset/js/util.js" charset="utf-8"></script>

<style>
    .layui-body {
        left: 30px !important;
    }

    .e {
        height: 600px;
        min-width: 1000px;
        font-size: 14px;
    }

    .type_btns {
        margin-top: 10px;
    }
</style>


{% endblock %}

{% block body %}


<div id="box_preview" style="display: none">
    <h1 class="site-h1">环境配置预览</h1>

    <form class="layui-form" action="" id="form_preview">


        <div class="layui-form-item">
            <label class="layui-form-label">环境配置</label>

            <div class="layui-input-block">
                <div class="e" id="editor_preview"></div>
                <script src="/asset/js/ace.js" type="text/javascript"
                        charset="utf-8"></script>

                <script>
                    var editor_preview = ace.edit("editor_preview");
                    editor_preview.setTheme("ace/theme/monokai");
                    editor_preview.getSession().setMode("ace/mode/yaml");

                    editor_preview.container.style.lineHeight = 2
                    editor_preview.container.style.fontSize = "14px"
                    editor_preview.renderer.updateFontSize()
                </script>

            </div>


        </div>


    </form>

</div>

<div class="layui-body">

    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li><a href="index2.html">应用配置</a></li>
            <li class="layui-this"><a href="index.html">环境配置</a></li>

            {% if permission.global_template %}
            <li class=""><a href="global_template.html">预设模板</a></li>
            {%endif %}
            <li class=""><a href="resource.html">资源管理</a></li>

        </ul>
        <div class="layui-tab-content"></div>
    </div>


    <h1 class="site-h1">环境配置管理</h1>

    <div class="env_btns">
        <button class="layui-btn layui-btn-primary " id="dev">dev</button>
        <button class="layui-btn layui-btn-primary " id="testenv">testenv</button>

        {% if permission.prod %}
        <button class="layui-btn layui-btn-primary " id="prod">prod</button>
        {% endif %}

    </div>

    <div class="type_btns">
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="host">服务host</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="redis">redis</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="nginx">nginx</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="mongo">mongo</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="mysql">mysql</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="apps">apps</button>

    </div>


    <div id="box">

        <form class="layui-form layui-form-pane" action="" id="item-form">
            <input type="text" name="_id" id="_id" style="display: none">

            <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">环境配置</label>
                <label class="layui-form-label" id="type_name"></label>

                <div class="layui-input-block">
                    <div class="e" id="editor"></div>
                    <script src="/asset/js/ace.js" type="text/javascript"
                            charset="utf-8"></script>

                    <script>
                        var editor = ace.edit("editor");
                        editor.setTheme("ace/theme/monokai");
                        editor.getSession().setMode("ace/mode/yaml");

                        editor.container.style.lineHeight = 2
                        editor.container.style.fontSize = "14px"
                        editor.renderer.updateFontSize()
                    </script>

                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
                    <button class="layui-btn layui-btn-normal" id="btn_validate">验证</button>
                    <button class="layui-btn layui-btn-normal" id="btn_preview">预览</button>

                </div>
            </div>

        </form>

    </div>


</div>

<script src="/asset/js/util.js" charset="utf-8"></script>
<script src="/asset/layui/layui.js" charset="utf-8"></script>

<script>
    layui.use(['table', "form"], function () {
        var $ = layui.$

        var env = getURLParameter("env") || "dev"
        var type = getURLParameter("type") || "host"

        function init_btns() {
            var ENV = ["prod", "testenv", "dev"]

            for (var ii in ENV) {
                console.log(ENV[ii])
                var $btn = $("#" + ENV[ii])
                if ($btn.attr("id") == env) {
                    $btn.removeClass("layui-btn-primary ")
                } else {
                    $btn.addClass("layui-btn-primary ")
                }
            }
        }

        function init_type_btns() {
            var TYPE = ["host", "redis", "mongo", "nginx", "mysql", "apps"]

            for (var ii in TYPE) {
                console.log(TYPE[ii])
                var $btn = $("#" + TYPE[ii])
                if ($btn.attr("id") == type) {
                    $btn.removeClass("layui-btn-primary ")
                } else {
                    $btn.addClass("layui-btn-primary ")
                }
            }
            $("#type_name").html(type + " : ")
        }

        function init_data() {
            $.ajax({
                url: "/env_config?env=" + env + "&type=" + type,
                type: "GET",
                success: function (_data) {
                    if (!_data.data) {
                        return
                    }
                    console.log(_data)
                    yaml_str = _data.data.yaml_str || ""
                    editor.setValue(yaml_str)
                    editor.gotoLine(1)
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        }

        init_data()
        init_btns()
        init_type_btns()
        init_bind(".env_btns", "env")
        init_bind(".type_btns", "type")


        function init_bind(cls, btn) {
            $(cls).find("button").on('click', function (event) {
                var $el = $(event.currentTarget)
                var $id = $el.attr("id")
                if (btn == "env") {
                    location.href = "index.html?env=" + $id + "&type=" + type
                } else {
                    location.href = "index.html?env=" + env + "&type=" + $id
                }
                console.log($el.attr("id"))
            });
        }

        $('#btn_validate').on('click', function (event) {
            event.preventDefault();
            try {
                s = jsyaml.load(editor.getValue())
                console.log(s)

                layer.alert('YAML验证通过', {
                    icon: 1,
                    skin: 'layer-ext-moon'
                })

            } catch (err) {
                console.log(err)
                layer.alert('YAML验证失败!<br>' + err, {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
            }

        });

        $('#btn_preview').on('click', function (event) {
            event.preventDefault()

            index = layer.open({
                type: 1,
                title: '预览',              // [可选]
                content: $('#box_preview'),          // 对话框中的内容部分
                area: ['1200px',],    // 对话框的大小 [可选]
                shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
            });
            var yaml_str = editor.getValue()
            set_rendered_content(yaml_str)
        });

        var form = layui.form

        //监听提交
        form.on('submit(demo1)', function (data) {
            var yaml_str;
            try {
                jsyaml.load(editor.getValue())
                yaml_str = editor.getValue()
                console.log(yaml_str)

            } catch (err) {
                console.log(err)
                layer.alert('YAML验证失败!<br>' + err, {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
                return false
            }
            data.field["yaml_str"] = yaml_str;
            data.field["env"] = env;
            data.field["type"] = type;

            $.ajax({
                url: "/env_config",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data.field),
                success: function (_data) {
                    layer.msg('更新成功');
                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            return false;
        });


        form.verify({
            yaml: function (value) {
                data = JSON.parse(value)
                if (data == null) {
                    return 'json 不合法';
                }
                return false
            }

        });


        function set_rendered_content(template_str) {
            var env = "dev",
                app_name = "accountcenter";

            var data = {"template": template_str, "env": env, "app_name": app_name}
            $.ajax({
                url: "/render_template",
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (_data) {
                    console.log(_data)
                    if (_data.code != 0) {
                        layer.alert('请求失败!<br>' + _data.message, {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })
                        return false

                    }
                    editor_preview.setValue(_data.data)
                    editor_preview.gotoLine(1)
                    editor_preview.setReadOnly(true)

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        }


    });

    function render_form($form, row) {
        if (!row) {
            $form.find('input').val("");
            $form.find('select').val("");
            $form.find('textarea').val("");
            return
        }
        for (var name in row) {
            $form.find('input[name="' + name + '"]').val(row[name]);
            $form.find('select[name="' + name + '"]').val(row[name]);
            $form.find('textarea[name="' + name + '"]').val(row[name]);
        }

    }
</script>
{% endblock %}
